package com.mumu.poi.excel;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.FileOutputStream;

/**
 * @author mumu
 * @version 1.0
 * @date 2024/1/8 16:00
 * @describe
 */
public class MergeGenerate {

    /**
     * createSheet创建sheet页
     * createCell创建单元格对象
     * CellRangeAddress类来指定行号和列号以及最后单元格的行号和列号
     * addMergedRegion方法来指定要合并的单元格范围
     *
     * @param args
     * @throws Exception
     */

    public static void main(String[] args) throws Exception {
        //文件路径
        String filePath = "excel/MergeGenerate.xls";
        //创建Excel文件(Workbook)
        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFSheet sheet = workbook.createSheet("Test");// 创建工作表(Sheet)
        HSSFRow row = sheet.createRow(0);
//合并列
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("合并列");
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 5);
        sheet.addMergedRegion(region);
//合并行
        cell = row.createCell(6);
        cell.setCellValue("合并行");
        region = new CellRangeAddress(0, 5, 7, 7);
        sheet.addMergedRegion(region);
        FileOutputStream out = new FileOutputStream(filePath);
        //保存Excel文件
        workbook.write(out);

        out.close();//关闭文件流
        System.out.println("OK!");

    }
}
